#ifndef MYSERVER_H
#define MYSERVER_H
#include <iostream>
#include <unistd.h>
#include "httplib.h"
#include <fstream>
#include <map>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <string>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#define EPOLL_SIZE 1024   //最大事件数

using namespace std;
using namespace httplib;

enum Type {HEART, OTHER};

struct PACKET_HEAD
{
    Type type;
    uint32_t length;
};

void* heart_handler(void* arg);
void* http_handler(void* arg);
void* update_handler(void* arg);

void handle_get_index(const httplib::Request& req, httplib::Response& res);
void handle_get_getfile(const httplib::Request& req, httplib::Response& res);
void handle_post_upload_update_file(const httplib::Request& req, httplib::Response& res);
void handle_post_update(const httplib::Request& req, httplib::Response& res);
void handle_get_update_state(const httplib::Request& req, httplib::Response& res);
void handle_post_update_state(const httplib::Request& req, httplib::Response& res);


class MyServer
{
public:
    MyServer();
    ~MyServer();
    bool GetConfig();
    void Bind();
    void Listen(int num = 10);
    void Accept();
    void Recv(int sockfd);
    void Run();
    void SetNoBlockMode(int sock = -1);
    void GetUpdateFileSize();
    void SendUpdateSignalToAll();
    friend void* heart_handler(void* arg);
    friend void* http_handler(void* arg);
    friend void* update_handler(void* arg);
    friend void handle_post_update(const httplib::Request& req, httplib::Response& res);
private:
    string listen_ipAddress;
    uint16_t listen_port;
    struct sockaddr_in server_addr;
    socklen_t server_addr_len;
    int listen_fd;    // 监听的fd
    int max_fd;       // 最大的fd
    struct epoll_event* ep_events;
    struct epoll_event event;
    int epfd;
    int ev_count;
    map<int, pair<string, uint8_t> > mmap;   // 记录连接的客户端fd--><ip, count>
    uint32_t update_file_size;
};

#endif // MYSERVER_H
